package com.sskj.common.util;

import com.sskj.common.dto.IPRegionInfo;
import jakarta.servlet.http.HttpServletRequest;
import org.lionsoul.ip2region.xdb.Searcher;
import java.io.File;
import java.util.Objects;

public class IPUtil {
    private static final String IP_UTILS_FLAG = ",";
    private static final String UNKNOWN = "unknown";
    private static final String LOCALHOST_IP = "0:0:0:0:0:0:0:1";
    private static final String LOCALHOST_IP1 = "127.0.0.1";

    /**
     * 获取IP地址
     * <p>
     * 使用Nginx等反向代理软件， 则不能通过request.getRemoteAddress()获取IP地址
     * 如果使用了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP地址，X-Forwarded-For中第一个非unknown的有效IP字符串，则为真实IP地址
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ip = null;
        try {
            //以下两个获取在k8s中，将真实的客户端IP，放到了x-Original-Forwarded-For。而将WAF的回源地址放到了 x-Forwarded-For了。
            ip = request.getHeader("X-Original-Forwarded-For");
            if (StrUtil.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("X-Forwarded-For");
            }
            //获取nginx等代理的ip
            if (StrUtil.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("x-forwarded-for");
            }
            if (StrUtil.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (StrUtil.isBlank(ip) || ip.isEmpty() || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (StrUtil.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (StrUtil.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            //兼容k8s集群获取ip
            if (StrUtil.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
                if (LOCALHOST_IP1.equalsIgnoreCase(ip) || LOCALHOST_IP.equalsIgnoreCase(ip)) {
                    //根据网卡取本机配置的IP
//                    InetAddress iNet = null;
//                    try {
//                        iNet = InetAddress.getLocalHost();
//                    } catch (UnknownHostException e) {
//                        log.error("Get ClientIp Error", e);
//                    }
//                    assert iNet != null;
//                    ip = iNet.getHostAddress();
                    ip = LOCALHOST_IP1;
                }
            }
        } catch (Exception ignored) {
        }
        //使用代理，则获取第一个IP地址
        if (!StrUtil.isBlank(ip) && ip.indexOf(IP_UTILS_FLAG) > 0) {
            ip = ip.substring(0, ip.indexOf(IP_UTILS_FLAG));
        }

        return ip;
    }

    /**
     * 根据IP获取地址位置
     * @param ip ip地址
     * @return 地理位置
     */
    public static IPRegionInfo getRegionByIP(String ip) {
        String ip2regionXdbPath = Objects.requireNonNull(IPUtil.class.getResource("/ip2region/ip2region.xdb")).getPath();
        File file = new File(ip2regionXdbPath);
        if (!file.exists()) {
            return null;
        }

        try {
            Searcher searcher = Searcher.newWithFileOnly(ip2regionXdbPath);

            String ip2RegionStr = searcher.search(ip);
            String[] split = ip2RegionStr.split("\\|");
            IPRegionInfo ipRegionInfo = new IPRegionInfo();
            ipRegionInfo.setCountry(split[0]);
            ipRegionInfo.setRegion(split[1]);
            ipRegionInfo.setProvince(split[2]);
            ipRegionInfo.setCity(split[3]);
            ipRegionInfo.setIsp(split[4]);

            return ipRegionInfo;
        } catch (Exception ignored) {}

        return null;
    }
}
